package main

import (
	"RedWork/gdao"
	"RedWork/model"
	"RedWork/rpc/userCenter/userCenter"
	"RedWork/service"
	"RedWork/service/etcd"
	"RedWork/service/etcdv2"
	"context"
	"flag"
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"google.golang.org/grpc"
	"log"
	"net"
)

type server struct {
	userCenter.UnimplementedRegisterCenterServer
}

var etcdCenter string = "127.0.0.1:2379"

//func Etcd() {
//	etcdClient, err := etcd.New(etcd.Config{
//		Endpoints:   []string{"127.0.0.1:2379"},
//		DialTimeout: 5 * time.Second,
//	})
//	if err != nil {
//		log.Println("etcd.New err: ", err)
//		return
//	}
//	defer etcdClient.Close()
//
//}
// etcdV1 不带选举，只适合单节点
func etcdV1(target string) {
	centerEtcd := etcd.NewCenterEtcd("127.0.0.1:2379")
	centerEtcd.AddNode(etcd.NewNode("jingdong", "user_center", target))
	go func() {
		for {
			select {
			case <-centerEtcd.AliveChan:
				log.Println("续约")
			}
		}
	}()
}

// etcdV2 支持多节点选举
func etcdV2(config *etcdv2.Config) (err error) {
	nodeServer, err := etcdv2.NewNodeServer(config)
	if err != nil {
		return err
	}

	err = nodeServer.StartServer()
	if err != nil {
		return err
	}
	return nil
}

func main() {
	addr := flag.String("addr", "err", "服务地址如127.0.0.1:8080")
	flag.Parse()
	listen, err := net.Listen("tcp", *addr)
	if err != nil {
		panic(err)
	}
	s := grpc.NewServer()
	userCenter.RegisterRegisterCenterServer(s, &server{})

	err = etcdV2(&etcdv2.Config{
		EleName:   "jingdong/user",            //选举的信息
		NodeName:  *addr,                      //节点的val
		Endpoints: []string{"127.0.0.1:2379"}, //etcd的服务地址
	})
	if err != nil {
		log.Println(err)
		return
	}

	fmt.Println("正在监听......")
	if err = s.Serve(listen); err != nil {
		log.Println(err)
		return
	}
}

func (s *server) Register(ctx context.Context, req *userCenter.RegisterReq) (res *userCenter.RegisterRes, err error) {
	userInfo := model.UserInfo{
		UserName: req.UserName,
		PassWord: req.PassWord,
	}
	res = &userCenter.RegisterRes{}
	uid, err := gdao.AddUser(userInfo)
	if err != nil {
		res.ID = 0
		res.Status = false
		return res, err
	}
	res.ID = uint32(uid)
	res.Status = true
	return res, nil
}

func (s *server) Login(ctx context.Context, req *userCenter.LoginReq) (res *userCenter.LoginRes, err error) {
	res = &userCenter.LoginRes{}
	user := model.UserInfo{
		UserName: req.UserName,
		PassWord: req.PassWord,
	}
	pw, uid, err := gdao.QueryUserPW(req.UserName)
	if err != nil {
		log.Println("不存在的输入")
		return
	}
	JwtKey := service.JWTKey{[]byte(service.PrivateKey)}
	token, err := JwtKey.CreateToken(service.MyClaims{
		UserID:         uid,
		UserName:       req.UserName,
		StandardClaims: jwt.StandardClaims{}, //过期时间在方法里面设置了
	})
	if err != nil {
		log.Println(err)
		return
	}

	if pw == user.PassWord {
		return &userCenter.LoginRes{
			Status: true,
			Token:  token,
		}, nil
	}
	return
}
